#!/usr/bin/env node
/*
 * simple http server
 *
 * @see http://stackoverflow.com/questions/6084360/using-node-js-as-a-simple-web-server
 */

'use strict';

const http = require('http'),
	url = require('url'),
	path = require('path'),
	fs = require('fs');

const contentTypesByExtension = {
	'.html': 'text/html',
	'.css':  'text/css',
	'.js':   'text/javascript'
};

function handleRequest (filename, response) {
	fs.exists(filename, (exists) => {
		if(!exists) {
			response.writeHead(404, {'Content-Type': 'text/plain'});
			response.write('404 Not Found\n');
			response.end();
			return;
		}

		if (fs.statSync(filename).isDirectory()) {
			handleRequest(filename + '/index.html', response);
			return;
		}

		fs.readFile(filename, 'binary', (err, file) => {
			if (err) {
				response.writeHead(500, {'Content-Type': 'text/plain'});
				response.write(err + '\n');
				response.end();
				return;
			}

			var headers = {};
			var contentType = contentTypesByExtension[path.extname(filename)];
			if (contentType) {
				headers['Content-Type'] = contentType;
			}
			response.writeHead(200, headers);
			response.write(file, 'binary');
			response.end();
		});
	});
}

function start (basedir, port, options) {
	options || (options = {});
	var server = http.createServer((request, response) => {
		try {
			var uri = url.parse(request.url).pathname,
				filename = path.join(process.cwd(), basedir, uri);

			//console.log(uri + '\t' + filename);

			if (uri == '/shutdown') {
				response.writeHead(200, {'Content-Type': 'text/plain'});
				response.write('Bye!\n');
				response.end();
				setTimeout(() => {
					server.close();
					server = null;
					if (!('noexit' in options) || !options.noexit) {
						process.exit(0);
					}
				}, 100);
				return;
			}

			handleRequest(filename, response);
		}
		catch (ex) {
			console.log('exception in www server: ' + ex);
		}
	});
	server.on('error', err => {
		console.log('exception: ' + err);
		process.exit(1);
	});
	server.listen(parseInt(port, 10), () => {
		if (!('silent' in options) || !options.silent) {
			console.log('started on http://localhost:' + port + '/');
			console.log('  - base directory: ' + basedir);
			console.log('  - Press CTRL+C or access /shutdown to shutdown');
		}
	});
}

try {
	if (path.basename(process.argv[1]) == path.basename(__filename)) {
		start(process.argv[3] || 'www', process.argv[2] || 8888);
	}
	else {
		exports.start = start;
	}
}
catch (ex) {
	console.log('exception: ' + ex);
	process.exit(1);
}

// vim:set ts=4 sw=4 fenc=UTF-8 ff=unix ft=javascript fdm=marker fmr=<<<,>>> :
